#include "stm8s.h"
#include "sched.h"
#include "qumi_config.h"
#include "misc.h"
#include "humidity.h"
#include "dewpoint_table.h"
/*#include "se8r01.h"*/
#include "nrf24.h"

extern uint8_t data_array[];

void Sched_Init(void)
{
  /* TIM4 Peripheral Configuration */ 
  /* Time Base configuration */
  TIM4_TimeBaseInit(TIM4_PRESCALER, TIM4_CCR_Val);
  
  /*TIM4 counter enable */
  TIM4_Cmd(ENABLE);
  
  TIM4_ITConfig(TIM4_IT_UPDATE, ENABLE);
}

void Sched_Task(void)
{
  static uint32_t cnt = 0;
  
  ++cnt;

#if 1
  if (cnt == SCHED_CNT_DAY)
  {
    //TODO: do Daily work
    cnt = 0;
    return;
  }

  //start adc
  if ((cnt % (SCHED_CNT_SECOND * 20)) == 0)
  {
    Humidity_Start(ENABLE);
    ADC1_StartConversion();
  }

  //send sensor data to server. every 30 seconds
  if ((cnt % (SCHED_CNT_SECOND * 30)) == 0)
  {
    /*Se8r01_Task();*/

    //send data to master
    data_array[0] = NRF24L01_SENSOR;
    data_array[1] = g_temp;
    data_array[2] = g_humi;
    data_array[3] = 77;

    /*IWDG_ReloadCounter();*/
    /* Automatically goes to TX mode */
    nrf24_send(data_array);        
        
    /* Wait for transmission to end */
    while(nrf24_isSending())
    {
      IWDG_ReloadCounter();
    }

    //powerdown
    nrf24_powerDown();
  }

#endif
}
